﻿Public Class PacketHandler

    Public handler As Handler

    Public Sub New(ByVal handler As Handler)
        Me.handler = handler
    End Sub

    Public Sub handlePacket(ByVal buf() As Byte, ByVal index As Integer, ByVal len As Integer)
        Dim header As Integer = buf(index)
        Select Case header
            Case &HFC
                handleLogin(buf, index + 4)
                Exit Select
            Case &H16
                handleKickPlayer(buf, index + 4)
                Exit Select
            Case Else
                log.log(LogType.MSG_RECV)
                For i As Integer = 0 To len - 1 Step i + 1
                    Console.Write("{0:x2} ", buf(i + index))
                Next
                Console.WriteLine()
                Exit Select
        End Select
    End Sub

    Public Sub handleLogin(ByVal buf() As Byte, ByVal index As Integer)
        Dim offset As Integer = index

        Dim client = PacketCreator.getString(buf, offset)
        Dim hash = PacketCreator.getString(buf, offset)
        Dim user = PacketCreator.getString(buf, offset)
        Dim pass = PacketCreator.getString(buf, offset)

        If (client <> "20070712") Then
            Packets.LoginError(&H8A, Me) 'Old Client
            Exit Sub
        End If
        log.log(LogType.MSG_INFO, "Login attempt User = " & user & " Pass = " & pass)
        Dim userid As Integer = -1
        Dim online As Integer = -1
        Dim accesslevel As Integer = -1
        If (MySQL.testLogin(user, pass, userid, online, accesslevel)) Then
            If (online <> 0) Then
                Packets.LoginError(&H67, Me) 'Already Connected
                Exit Sub
            ElseIf (accesslevel = 0) Then
                Packets.LoginError(&H77, Me) 'Banned
                Exit Sub
            Else
                MySQL.setOnline(userid, 1)
                handler.userID = userid
                Packets.ServerList(user, Me) 'Success
                Exit Sub
            End If
        Else
            Packets.LoginError(&H78, Me) 'Invalid Username Or Password
            Exit Sub
        End If
    End Sub

    Public Sub handleKickPlayer(ByVal buf() As Byte, ByVal index As Integer)
        Dim offset As Integer = index

        Dim user As String = PacketCreator.getString(buf, offset)
        Dim pass As String = PacketCreator.getString(buf, offset)

        Dim userid As Integer = -1
        If (MySQL.testLogin(user, pass, userid, Nothing, Nothing)) Then
            MySQL.setOnline(userid, 0)
            For Each handler As Handler In SocketListener.clients
                If (handler.userID = userid) Then
                    handler.workSocket.Close()
                    Exit For
                End If
            Next
        End If
    End Sub

End Class
